package com.symaster.gameengine.util;

import com.symaster.gameengine.core.Component;
import com.symaster.gameengine.e2d.Scene;
import com.symaster.gameengine.e2d.transform.Transform;

import java.util.Set;

/**
 * @author yinmiao
 * @version 2023/11/15
 */
public class SceneUtil {

    /**
     * 获取某个组件的场景坐标(在场景中的坐标)
     *
     * @param component 指定组件
     * @return 组件的场景坐标(在场景中的坐标)
     */
    public static Transform toSceneTransform(Component component) {
        Transform rtn = new Transform();

        Transform transform = component.getComponent(Transform.class);

        if (transform == null) {
            rtn.x = 0;
            rtn.y = 0;
        } else {
            rtn.x = transform.x;
            rtn.y = transform.y;
        }

        if (component.getParent() != null && !(component.getParent() instanceof Scene)) {
            toSceneTransform(rtn, component.getParent());
        }

        return rtn;
    }

    public static void resourceLoad(Scene scene) {
        for (Component component : scene.getComponents()) {
            component.resourceLoad();

            Set<Component> components = component.getComponents();
            if (!components.isEmpty()) {
                // 加载子节点的资源
                childResourceLoad(components);
            }
        }
    }

    public static int autoMax(int camera, int canvas) {
        if (camera <= 0) {
            return canvas;
        } else {
            return camera;
        }
    }

    private static void toSceneTransform(Transform transform, Component parent) {
        Transform parentTransform = parent.getComponent(Transform.class);
        if (parentTransform != null) {
            transform.xAdd(parentTransform.x);
            transform.yAdd(parentTransform.y);
        }

        if (parent.getParent() != null && !(parent.getParent() instanceof Scene)) {
            toSceneTransform(transform, parent.getParent());
        }
    }

    private static void childResourceLoad(Set<Component> components) {
        for (Component component : components) {
            component.resourceLoad();

            Set<Component> components1 = component.getComponents();
            if (!components1.isEmpty()) {
                childResourceLoad(components1);
            }
        }
    }
}
